package com.alinesno.cloud.common.web.base.exceptions;


import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSONObject;
import com.alinesno.cloud.common.facade.response.ResponseBean;

/**
 * Web异常切面，处理Dubbo返回的异常信息
 * @author WeiXiaoJin
 * @since 2019年9月18日 上午8:06:19
 */
@Aspect
@Component
public class WebExceptionAspect {
	private static final Logger log = LoggerFactory.getLogger(WebExceptionAspect.class);

	@Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)"
			+ "||@annotation(org.springframework.web.bind.annotation.GetMapping)"
			+ "||@annotation(org.springframework.web.bind.annotation.PostMapping)"
			)
	private void webPointcut() {
	}

	/**
	 * 拦截web层异常，记录异常日志，并返回友好信息到前端 目前只拦截Exception，是否要拦截Error需再做考虑
	 * 
	 * @param e
	 *            异常对象
	 * @throws IOException 
	 */
	@AfterThrowing(pointcut = "webPointcut()", throwing = "e")
	public void handleThrowing(Exception e) throws IOException {
		ResponseBean response = WebExceptionUtils.handleException(e, null , null) ; 
		this.writeContent(response);
	}

	/**
	 * 将内容输出到浏览器
	 *
	 * @param content
	 *            输出内容
	 * @throws IOException 
	 */
	private void writeContent(ResponseBean content) throws IOException {
		HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		
		// 判断是否为ajax请求
		boolean isAjax = WebExceptionUtils.isAjax(request) ; 
		if(!isAjax) {
			WebExceptionUtils.errorRedirect(null , request, response) ; 
			return ; 
		}
		
		response.reset();
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Content-Type", "application/json;charset=UTF-8");
		response.setHeader("icop-content-type", "exception");
		PrintWriter writer = null;
		try {
			writer = response.getWriter();
		} catch (IOException e) {
			log.error("获取response异常:{}" , e);
		}
			
		writer.print(JSONObject.toJSON(content));
			
		writer.flush();
		writer.close();
	}
}